//
//  BoutiqueVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/15.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "BoutiqueVC.h"
#import <UIColor+Wonderful.h>
#import <AFHTTPSessionManager.h>
#import <AFNetworking.h>
#import "BoutiqueCell.h"
#import "BoutiqueModal.h"
#import <UIImageView+WebCache.h>
#import "BoutiqueDetailPageVC.h"
#import <MJRefresh.h>
#import "DesignVC.h"
#import "CompanyVC.h"
#import "BuyVC.h"
#import "InspirationVC.h"
#import "DiaryVC.h"
#import "OldHouseVC.h"
#import "GoodsVC.h"
#import "MatchingVC.h"
#import "SaveMoneyVC.h"
#import "DisperseBtn.h"/**< 散开的按钮 */

@interface BoutiqueVC () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableview;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger number;/**< 用来保存上拉加载时变化的数字 */
@property (nonatomic, retain) DisperseBtn *disView; /**< 散开的按钮 */
@end

@implementation BoutiqueVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //navigation设置
    self.navigationItem.title = @"精选";
    self.tabBarController.tabBar.tintColor = [UIColor aquamarine];
    
    // 数据处理
    [self dataHandler];
    // 初始化视图
    [self createSubviews];
    
    // 导航栏和tabBar的隐藏
    [self hidden];
    
    //给保存上拉加载的数字设置初始值
    self.number = 2;
    // 下拉刷新
    [self refresh];
}

/// 数据处理方法
- (void)dataHandler
{
    // 获取数据
    NSString *urlStr = @"http://ihome.cmfmobile.com:8080/sp/custom/getIndexProjectList.do?pn=1";

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        //        NSLog(@"%@", responseObject);
        
        NSMutableArray *arr = responseObject;
        self.dataArr = [BoutiqueModal modelHanderWithArray:arr];
        //判断字典里面有没有名字这个属性
        //如果字典里面没有就删除这个字典
        
        NSMutableArray *array = [NSMutableArray arrayWithArray:self.dataArr];
        
        for (int i = 0; i < array.count; i++) {
            BoutiqueModal *modal = array[i];
            if (modal.name == nil) {
                [_dataArr removeObject:modal];
            }
        }
        
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
        NSLog(@"%@", error);
    }];
    [self.tableview.mj_header endRefreshing];
}

/// 初始化视图
- (void)createSubviews
{
    // tableView的创建
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [_tableview registerClass:[BoutiqueCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableview];
    
    //散开的按钮
    DisperseBtn *disView = [[DisperseBtn alloc] init];
    // 设置按钮的初始位置
    disView.frame = CGRectMake(self.view.frame.size.width / 5 * 3, self.view.frame.size.height / 4 * 3, 50, 50);
    // 设置按钮的可以适应的边界
    disView.borderRect = self.view.bounds;
    // 设置按钮的两个不同的状态的图片
    disView.closeImage = [UIImage imageNamed:@"home1"];
    disView.openImage = [UIImage imageNamed:@"home2"];
    // 加入到主视图上
    [self.view addSubview:disView];
    _disView = disView;
    // 设置按钮个数
    [self setDisViewButtonsNum:8];

    
}

// 设置按钮的方法实现
- (void)setDisViewButtonsNum:(int)num
{
    [_disView recoverBotton];
    
    for (UIView *btn in _disView.btns) {
        [btn removeFromSuperview];
    }
    
    //按钮数组 (需要ARC模式)
    NSMutableArray *buttonArr = [NSMutableArray array];
    //装修设计按钮
    UIButton *designerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [designerButton setImage:[[UIImage imageNamed:@"button1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    [buttonArr addObject:designerButton];
    designerButton.tag = 1000;
    [designerButton addTarget:self action:@selector(designAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //装修公司按钮
    UIButton *companyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [companyButton setImage:[[UIImage imageNamed:@"button2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    [buttonArr addObject:companyButton];
    companyButton.tag = 2000;
    [companyButton addTarget:self action:@selector(companyAction:) forControlEvents:UIControlEventTouchUpInside];
    //团购按钮
    UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [buyButton setImage:[[UIImage imageNamed:@"button3"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [buttonArr addObject:buyButton];
    buyButton.tag = 3000;
    [buyButton addTarget:self action:@selector(buyAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //装修日记按钮
    UIButton *diaryButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [diaryButton setImage:[[UIImage imageNamed:@"button4"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [buttonArr addObject:diaryButton];
    diaryButton.tag = 4000;
    [diaryButton addTarget:self action:@selector(diaryAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //旧房装修按钮
    UIButton *oldHouseButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [oldHouseButton setImage:[[UIImage imageNamed:@"button5"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [buttonArr addObject:oldHouseButton];
    oldHouseButton.tag = 5000;
    [oldHouseButton addTarget:self action:@selector(oldHouseAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //省钱秘笈按钮
    UIButton *saveMoneyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [saveMoneyButton setImage:[[UIImage imageNamed:@"button6"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [buttonArr addObject:saveMoneyButton];
    saveMoneyButton.tag = 6000;
    [saveMoneyButton addTarget:self action:@selector(saveMoneyAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //装修搭配按钮
    UIButton *matchingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [matchingButton setImage:[[UIImage imageNamed:@"button7"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [buttonArr addObject:matchingButton];
    matchingButton.tag = 7000;
    [matchingButton addTarget:self action:@selector(matchingAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //买买买按钮
    UIButton *goodsButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [goodsButton setImage:[[UIImage imageNamed:@"button8"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [buttonArr addObject:goodsButton];
    goodsButton.tag = 8000;
    [goodsButton addTarget:self action:@selector(goodsAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 给中心按钮添加散开的按钮
    _disView.btns = [buttonArr copy];

}
/// 设置cell个数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

/// 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BoutiqueCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        BoutiqueModal *m = _dataArr[indexPath. row];
        NSMutableArray *arr = m.imageUrl;
        [cell.img sd_setImageWithURL:[NSURL URLWithString:arr[0]]];
        cell.titleLabel.text = m.name;
        cell.styleLabel.text = m.style;
        cell.squareLabel.text = m.space;
        cell.priceLabel.text = m.price;
        return cell;
    }else{
        return cell;
    }
}
/// 设置cell高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 230;
}

/// 点击cell进入详情页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BoutiqueDetailPageVC *boutiqueDetailVC = [[BoutiqueDetailPageVC alloc] init];
    BoutiqueModal *m = _dataArr[indexPath.row];
    boutiqueDetailVC.modal = m;
    [self.navigationController pushViewController:boutiqueDetailVC animated:YES];
    
}

/// 导航栏隐藏
- (void)hidden
{
    // 导航栏隐藏设置
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        // 取消ScrollView的内容自动调整
        self.automaticallyAdjustsScrollViewInsets = NO;
        //tableView边界预留
        UIEdgeInsets insets = self.tableview.contentInset;
        // 让上边界的预留值和导航栏相等
        insets.top = self.navigationController.navigationBar.bounds.size.height;
        //把修改后的边界预留值赋给tableView
        self.tableview.contentInset = insets;
        // 滚动指标点到滚到视图的边缘的距离
        self.tableview.scrollIndicatorInsets = insets;
    }
}

// 导航栏滚动
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}

/// 下拉刷新, 上拉加载
- (void)refresh
{
    // 下拉刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    // 开始刷新
    [self.tableview.mj_header beginRefreshing];
    
    
    //上拉加载
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //如果数据字典不为空 那么就刷新请求新的数据
    if (_dataArr.count != 0) {
        [self.tableview.mj_footer beginRefreshing];
    }
    
}

/// 上拉加载方法
- (void)loadNewData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://ihome.cmfmobile.com:8080/sp/custom/getIndexProjectList.do?pn=%ld", self.number];
   AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"精选加载更多成功");
        // 定义一个数组 用来保存新请求到的数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [BoutiqueModal modelHanderWithArray:responseObject];
//
//        NSMutableArray *Arr = [NSMutableArray arrayWithArray:newDataArr];
//        //判断字典里面有没有名字这个属性
//        //如果字典里面没有就删除这个字典
//        
//        NSMutableArray *array = [NSMutableArray arrayWithArray:self.dataArr];
//        
//        for (int i = 0; i < array.count; i++) {
//            BoutiqueModal *modal = array[i];
//            if (modal.name == nil) {
//                [Arr removeObject:modal];
//            }
//        }
        
//        NSArray *arrr = [NSArray arrayWithArray:Arr];
        
        //将新请求到的数据依次载入到保存数据的数组里面
        for (NSInteger i = 0; i < newDataArr.count; i++) {
            [self.dataArr addObject:newDataArr[i]];
        }
        // 刷新tableView
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"精选加载更多失败");
    }];
    
    // 结束刷新
    [self.tableview.mj_footer endRefreshing];
    //将保存刷新的动态数据加一
    self.number += 1;
}

//散开按钮中 设计按钮的点击事件
- (void)designAction:(UIButton *)sender
{
    // 跳转到设计的界面
    DesignVC *designVC = [[DesignVC alloc] init];
    [self.navigationController pushViewController:designVC animated:YES];
}

//散开按钮中 公司按钮的点击事件
- (void)companyAction:(UIButton *)sender
{
    // 跳转到设计的界面
    CompanyVC *companyVC = [[CompanyVC alloc] init];
    [self.navigationController pushViewController:companyVC animated:YES];
}

//散开按钮中 团购按钮的点击事件
- (void)buyAction:(UIButton *)sender
{
    // 跳转到设计的界面
    BuyVC *buyVC = [[BuyVC alloc] init];
    [self.navigationController pushViewController:buyVC animated:YES];
}

//散开按钮中 日记按钮的点击事件
- (void)diaryAction:(UIButton *)sender
{
    // 跳转到设计的界面
//    InspirationVC *inspirationVC = [[InspirationVC alloc] init];
//    [self.navigationController pushViewController:inspirationVC animated:YES];
    
    DiaryVC *diaryVC = [[DiaryVC alloc] init];
    [self.navigationController pushViewController:diaryVC animated:YES];
    
}

//散开按钮中 旧房装修按钮的点击事件
- (void)oldHouseAction:(UIButton *)sender
{
    
    OldHouseVC *oldHouseVC = [[OldHouseVC alloc] init];
    [self.navigationController pushViewController:oldHouseVC animated:YES];
    
}

//散开按钮中 省钱秘笈按钮的点击事件
- (void)saveMoneyAction:(UIButton *)sender
{
    
    SaveMoneyVC *saveMoneyVC = [[SaveMoneyVC alloc] init];
    [self.navigationController pushViewController:saveMoneyVC animated:YES];
    
}

//散开按钮中 装修搭配按钮的点击事件
- (void)matchingAction:(UIButton *)sender
{
    
    MatchingVC *matchingVC = [[MatchingVC alloc] init];
    [self.navigationController pushViewController:matchingVC animated:YES];
    
}

//散开按钮中 买买买按钮的点击事件
- (void)goodsAction:(UIButton *)sender
{
    
    GoodsVC *goodsVC = [[GoodsVC alloc] init];
    [self.navigationController pushViewController:goodsVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
